package com.defan.api.main;

import com.alibaba.fastjson.JSON;
import com.defan.api.utils.JSONUtils;
import com.defan.api.utils.MessUtils;
import com.defan.api.utils.RequestUtils;
import com.defan.api.utils.ShowDocUtils;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 张俊强~ on 2017/10/17.
 */
public class ApiAutoBuilderFace  {
    public static void main(String[] args) {
        WinUI winUI = new WinUI("接口文档自动生成器");
        winUI.setBounds(290, 100, 950, 540);
        winUI.setVisible(true);
        winUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        winUI.setWinUILayout();
        winUI.setActionEventLiatener();
        winUI.validate();
    }
}

class WinUI extends JFrame implements ActionListener {

    //页面上的一下要用到的控件

    private JLabel catNameLabel = null;        //一级目录显示信息
    private JComboBox catNameComboBox = null;     //一级目录
    private JComboBox subCatNameComboBox = null;  //二级目录
    private JLabel subCatNameLabel = null;     //二级目录显示信息
    private JLabel urlLabel = null;     //二级目录接口显示信息
    private JTextField urlTextField = null;       //输入url接口的输入框
    private JTextField pageTitleField = null;       //接口显示名称
    private JLabel paramsLabel=null;            //
    private JTextArea paramsTextArea = null;     //输入Raw参数
    private JButton submitButton = null;       //发送请求的按钮
    private JTextArea resultTextArea = null;     //显示一些过程信息
    //页面控件（第二级）
    private JLabel headerInfoLabel=null;        //设置 header 信息
    private JTextField headerKeyTextField=null; //header 的 Key
    private JTextField headerValueTextField=null;//header 的 Value
    private JButton addHeaderButton=null;    //添加header的按钮
    private JButton deleteHeaderButton=null;    //删除header的按钮

    private JScrollPane paramsScrollPane=null;
    private JScrollPane resultScrollPane=null;

    public WinUI(String title) {
        super(title);
        //实例化页面控件(顶部)
        catNameLabel = new JLabel();
        subCatNameLabel = new JLabel();
        catNameComboBox = new JComboBox();
        subCatNameComboBox = new JComboBox();
        urlLabel=new JLabel();
        urlTextField = new JTextField();

        paramsTextArea = new JTextArea(10,20);
        submitButton = new JButton();
        resultTextArea = new JTextArea(25,50);

        //实例化页面控件（第二级）
        headerInfoLabel=new JLabel("报文头：");
        headerKeyTextField=new JTextField(10);
        headerValueTextField=new JTextField(20);
        addHeaderButton=new JButton("添加");
        deleteHeaderButton=new JButton("清空");

        paramsLabel=new JLabel("输入Raw数据信息:");

        paramsScrollPane=new JScrollPane(paramsTextArea);
        resultScrollPane=new JScrollPane(resultTextArea);
        pageTitleField=new JTextField(10);
    }

    public void setComponentInfo(){
        catNameLabel.setText("一级目录");
        subCatNameLabel.setText("二级目录");
        catNameComboBox.addItem("登录注册");
        catNameComboBox.addItem("我的待办");
        catNameComboBox.addItem("我的申请");
        catNameComboBox.addItem("业务申请");
        catNameComboBox.addItem("功能导航");
        catNameComboBox.addItem("通讯录");
        catNameComboBox.addItem("流程平台");
        catNameComboBox.addItem("流程表单");
        catNameComboBox.addItem("通用");

        subCatNameComboBox.addItem("");
        subCatNameComboBox.addItem("表单管理");
        subCatNameComboBox.addItem("流程管理");
        subCatNameComboBox.addItem("审批角色");
        subCatNameComboBox.addItem("数据字典");
        subCatNameComboBox.addItem("流程分类");
        subCatNameComboBox.addItem("授权管理");
        subCatNameComboBox.addItem("流水码管理");
        subCatNameComboBox.addItem("流程报表");
        submitButton.setText("发送数据");
        urlLabel.setText("输入接口");

        urlTextField.setColumns(30);

        headerKeyTextField.setToolTipText("格式：[ \"DF_KEY\", \"QZTkrUlwWOLdMUqgkozvbmUzUdsWmJxN\" ]");
        headerKeyTextField.setText("DF_KEY");
        headerValueTextField.setToolTipText("格式：[ \"DF_KEY\", \"QZTkrUlwWOLdMUqgkozvbmUzUdsWmJxN\" ]");
        headerValueTextField.setText("QZTkrUlwWOLdMUqgkozvbmUzUdsWmJxN");
        pageTitleField.setToolTipText("请输入当前接口的名称");
        urlTextField.setText("http://idmdev.cscecdf.com/DCloudApi/DBPM/taskApplyQuery/taskApplyQueryService");
        pageTitleField.setText("获取我的申请列表");
        paramsTextArea.setText("{\"fields\":[{\"field\":\"task_number\",\"op\":\"like\",\"value\":\"\"}],\"page\":1,\"size\":10}");

    }
    public void setWinUILayout() {
        //设置界面的顶部部分
        setComponentInfo();
        JPanel jp1 = new JPanel();
        jp1.setLayout(new FlowLayout());
        jp1.add(catNameLabel);
        jp1.add(catNameComboBox);
        jp1.add(subCatNameLabel);
        jp1.add(subCatNameComboBox);
        jp1.add(urlLabel);
        jp1.add(urlTextField);
        jp1.add(submitButton);
        jp1.add(pageTitleField);
        jp1.setBorder(BorderFactory.createEtchedBorder());
        this.add(jp1,BorderLayout.NORTH);

        //设置页面的中间部分
        JPanel centerJp = new JPanel();

        JPanel jp2=new JPanel();
        jp2.setLayout(new FlowLayout());
        jp2.add(headerInfoLabel);
        jp2.add(headerKeyTextField);
        jp2.add(headerValueTextField);
        jp2.add(addHeaderButton);
        jp2.add(deleteHeaderButton);
        jp2.setBorder(BorderFactory.createEtchedBorder());
        centerJp.add(jp2,BorderLayout.NORTH);

        JPanel jp3=new JPanel();
        jp3.add(resultTextArea);
        centerJp.add(jp3,BorderLayout.CENTER);

        JPanel jp4=new JPanel();
        jp4.add(paramsLabel,BorderLayout.EAST);
        jp4.add(paramsTextArea, BorderLayout.CENTER);
        jp4.setBorder(BorderFactory.createEtchedBorder());
        this.add(jp4, BorderLayout.EAST);

        centerJp.setBorder(BorderFactory.createLineBorder(Color.gray, 1) );
        this.add(centerJp,BorderLayout.CENTER);

        paramsScrollPane.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        paramsScrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        resultScrollPane.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        resultScrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        paramsTextArea.setLineWrap(true);
        resultTextArea.setLineWrap(true);
    }

    public void setActionEventLiatener(){
        submitButton.addActionListener(this);
        deleteHeaderButton.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==deleteHeaderButton){
            resultTextArea.setText("");
            urlTextField.setText("");
            pageTitleField.setText("");
            paramsTextArea.setText("");
        }

        if(e.getSource()==submitButton){

            resultTextArea.setText("");

            System.out.println("正在相应按钮点击事件……");

            resultTextArea.append("**正在响应请求……**\n\n");
            resultTextArea.validate();
             String method = "";
             String headerStr = "";

            /**
             * 得到 要测试的接口返回的数据
             * */
            String responseInfo="";
            Map requestHeader = new HashMap();
            String requestUrl = urlTextField.getText().trim();
            String requestParam = paramsTextArea.getText().trim();
            requestHeader.put(headerKeyTextField.getText().trim(),headerValueTextField.getText().trim());
//            requestHeader.put("DF_KEY", "ZTOjkhcNdwZQcCzLRexRinIsVzEArbsj");
            try {
                responseInfo = RequestUtils.getResponseMess(requestUrl, requestParam, requestHeader);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.out.println("**接口返回数据**\n\n"+responseInfo+"\n\n");
            resultTextArea.append("**接口成功返回数据**\n\n");
            resultTextArea.validate();

            /**
             * 生成相应的接口信息
             * */
            Map requestParams = new HashMap();
            method = "POST";
            headerStr = "{}";
            requestParams.put("url", requestUrl);
            requestParams.put("method", method);
            requestParams.put("param_str", MessUtils.TableTitle+ JSONUtils.formatJsonToParamTable(requestParam));
            requestParams.put("param_json", JSONUtils.formatJson(requestParam));
            responseInfo = JSONUtils.simplifyJsonArrayNumber(responseInfo, 2);
            System.out.println(JSONUtils.formatJson(responseInfo));
            requestParams.put("result_text", JSONUtils.formatJson(responseInfo));
            requestParams.put("result_table", MessUtils.OutputTableTitle+JSONUtils.formatJsonToOutputTable(responseInfo));

            responseInfo = ShowDocUtils.formatToMardown(requestParams);
            resultTextArea.append("***正在生成文档信息……***\n\n");
            System.out.println("***生成文档信息***\n\n"+responseInfo+"\n\n");
            /**
             * 将接口文档信息发布到 ShowDoc 上去
             * */
            resultTextArea.append("正在发布接口……\n\n");
            resultTextArea.validate();
            try {
                String catName=catNameComboBox.getSelectedItem().toString();
                String subCatName=subCatNameComboBox.getSelectedItem().toString();
                String pageTitle=pageTitleField.getText();
                String responseResult = ShowDocUtils.getMDResultText(responseInfo, "99",catName,subCatName,pageTitle);
                resultTextArea.append("接口发布成功！\n所在目录：["+catNameComboBox.getSelectedItem().toString()+"\\"+subCatNameComboBox.getSelectedItem().toString()+"]\n\n");
                System.out.println("接口发布成功！\n\n[返回信息]:\n" + JSONUtils.formatJson(responseResult));
                String pageId=(JSON.parseObject(JSON.parseObject(responseResult).get("data").toString())).get("page_id").toString();
                resultTextArea.append("文档访问链接： https://www.showdoc.cc/DcloudAPI?page_id="+pageId );
                resultTextArea.validate();
            } catch (IOException e1) {
                resultTextArea.setText("接口发布失败！\n\n");
                resultTextArea.append(e1.getMessage());
                resultTextArea.validate();
            }
        }
    }
}
